/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sys.web;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.merge.LoopMergeStrategy;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.scoreacademicyear.entity.ScoreAcademicYear;
import com.jeeplus.modules.scoreacademicyear.mapper.ScoreAcademicYearMapper;
import com.jeeplus.modules.scoreacademicyear.service.ScoreAcademicYearService;
import com.jeeplus.modules.sys.entity.*;
import fr.opensagres.xdocreport.core.XDocReportException;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import fr.opensagres.xdocreport.template.formatter.FieldsMetadata;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.jeeplus.modules.sys.service.StudentMoreduMainService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.xml.crypto.Data;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 学生德育档案Controller
 * @author 于昭龙 赵炫曾
 * @version 2022-02-11
 */
@RestController
@RequestMapping(value = "/moredumain/studentMoreduMain")
public class StudentMoreduMainController extends BaseController {

	@Autowired
	private StudentMoreduMainService studentMoreduMainService;

	@Autowired
	private ScoreAcademicYearService scoreAcademicYearService;

	@Autowired
	private ScoreAcademicYearMapper scoreAcademicYearMapper;

	@Autowired
	private RedisTemplate<String,Object> redisTemplateObject;


	@ModelAttribute
	public StudentMoreduMain get(@RequestParam(required=false) String id ,String time) {
		StudentMoreduMain entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = studentMoreduMainService.get(id,time);
		}
		if (entity == null){
			entity = new StudentMoreduMain();
		}
		return entity;
	}

	/**
	 * 学生德育档案列表数据
	 */
	@RequiresPermissions("moredumain:studentMoreduMain:list")
	@GetMapping("list")
	public AjaxJson list(StudentMoreduMain studentMoreduMain, HttpServletRequest request, HttpServletResponse response) {
		boolean is = false;
		Enumeration enu=request.getParameterNames();
		while(enu.hasMoreElements()){
			String paraName=(String)enu.nextElement();
			if (paraName.equals("maximum"))
				is = true;
			System.out.println(paraName+": "+request.getParameter(paraName));
		}
		if (is == true) {
			String maximum = request.getParameter("maximum");
			String minimum = request.getParameter("minimum");
			Integer max = 0, min = 0;
			if (maximum.length() == 0) {
				max = Integer.MAX_VALUE;
			} else {
				max = Integer.parseInt(maximum);
			}
			if (minimum.length() == 0) {
				min = Integer.MIN_VALUE;
			} else {
				min = Integer.parseInt(minimum);
			}
			studentMoreduMain.setMax(max);
			studentMoreduMain.setMin(min);
		}
		if (studentMoreduMain.getQueryAcademicYear() != null && !"".equals(studentMoreduMain.getQueryAcademicYear())) {
			String[] interval = studentMoreduMain.getQueryAcademicYear().split(",");
			int minYear = 9999;
			int maxYear = 0;
			for(String temp : interval) {
				String[] ab = temp.split("-");
				int a = Integer.parseInt(ab[0]);
				int b = Integer.parseInt(ab[1]);
				if (a < minYear)
					minYear = a;
				if (b > maxYear)
					maxYear = b;
			}
			studentMoreduMain.setQueryAcademicYear(minYear + "-" + maxYear);
			DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			LocalDate stdate = LocalDate.parse(minYear+"-09-01",dtf);
			LocalDate endate = LocalDate.parse(maxYear+"-08-01",dtf);
			studentMoreduMain.setStartDate(Date.from(stdate.atTime(LocalTime.MIDNIGHT).atZone(ZoneId.systemDefault()).toInstant()));
			studentMoreduMain.setEndDate(Date.from(endate.atTime(LocalTime.MIDNIGHT).atZone(ZoneId.systemDefault()).toInstant()));
		}
		System.out.println(studentMoreduMain.toString());
		Page<StudentMoreduMain> page = studentMoreduMainService.findPage(new Page<StudentMoreduMain>(request, response), studentMoreduMain);
//		ScoreAcademicYear scoreAcademicYear = scoreAcademicYearMapper.findScoreByYear(studentMoreduMain);
//		for (StudentMoreduMain smm : page.getList()){
//			System.out.println(smm.toString());
//			smm.setCurrentMoraleduPoint(smm.getCurrentMoraleduPoint() + (int)Double.parseDouble(scoreAcademicYear.getScore()));;
//		}
		return AjaxJson.success().put("page",page);
	}

	/**
	 *
	 * @param studentMoreduMain
	 * @param request
	 * @param response
	 * @return
	 */
	@RequiresPermissions("moredumain:studentMoreduMain:list")
	@GetMapping("sort")
	public AjaxJson sort(StudentMoreduMain studentMoreduMain, HttpServletRequest request, HttpServletResponse response) {
		boolean is = false;
		Enumeration enu=request.getParameterNames();
		while(enu.hasMoreElements()){
			String paraName=(String)enu.nextElement();
			if (paraName.equals("maximum"))
				is = true;
			System.out.println(paraName+": "+request.getParameter(paraName));
		}
		if (is == true) {
			String maximum = request.getParameter("maximum");
			String minimum = request.getParameter("minimum");
			Integer max = 0, min = 0;
			if (maximum.length() == 0) {
				max = Integer.MAX_VALUE;
			} else {
				max = Integer.parseInt(maximum);
			}
			if (minimum.length() == 0) {
				min = Integer.MIN_VALUE;
			} else {
				min = Integer.parseInt(minimum);
			}
			studentMoreduMain.setMax(max);
			studentMoreduMain.setMin(min);
		}
		Page<StudentMoreduMain> page = studentMoreduMainService.sort(new Page<StudentMoreduMain>(request, response), studentMoreduMain);
		return AjaxJson.success().put("page",page);
	}

	/**
	 * 查询未审核
	 */
	@RequiresPermissions("moredumain:studentMoreduMain:list")
	@GetMapping("queryNot")
	public AjaxJson queryNot(StudentMoreduMain studentMoreduMain, HttpServletRequest request, HttpServletResponse response) {
		boolean is = false;
		Enumeration enu=request.getParameterNames();
		while(enu.hasMoreElements()){
			String paraName=(String)enu.nextElement();
			if (paraName.equals("maximum"))
				is = true;
			System.out.println(paraName+": "+request.getParameter(paraName));
		}
		if (is == true) {
			String maximum = request.getParameter("maximum");
			String minimum = request.getParameter("minimum");
			Integer max = 0, min = 0;
			if (maximum.length() == 0) {
				max = Integer.MAX_VALUE;
			} else {
				max = Integer.parseInt(maximum);
			}
			if (minimum.length() == 0) {
				min = Integer.MIN_VALUE;
			} else {
				min = Integer.parseInt(minimum);
			}
			studentMoreduMain.setMax(max);
			studentMoreduMain.setMin(min);
		}
		if (studentMoreduMain.getQueryAcademicYear() != null && !"".equals(studentMoreduMain.getQueryAcademicYear())) {
			String[] interval = studentMoreduMain.getQueryAcademicYear().split(",");
			int minYear = 9999;
			int maxYear = 0;
			for(String temp : interval) {
				String[] ab = temp.split("-");
				int a = Integer.parseInt(ab[0]);
				int b = Integer.parseInt(ab[1]);
				if (a < minYear)
					minYear = a;
				if (b > maxYear)
					maxYear = b;
			}
			studentMoreduMain.setQueryAcademicYear(minYear + "-" + maxYear);
			DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			LocalDate stdate = LocalDate.parse(minYear+"-09-01",dtf);
			LocalDate endate = LocalDate.parse(maxYear+"-08-01",dtf);
			studentMoreduMain.setStartDate(Date.from(stdate.atTime(LocalTime.MIDNIGHT).atZone(ZoneId.systemDefault()).toInstant()));
			studentMoreduMain.setEndDate(Date.from(endate.atTime(LocalTime.MIDNIGHT).atZone(ZoneId.systemDefault()).toInstant()));
		}
		Page<StudentMoreduMain> page = studentMoreduMainService.queryNot(new Page<StudentMoreduMain>(request, response), studentMoreduMain);
		return AjaxJson.success().put("page",page);
	}

	/**
	 * 学生德育档案列表数据
	 */
	@RequiresPermissions("moredumain:studentMoreduMain:list")
	@GetMapping("queryDetail")
	public AjaxJson queryDetail(StudentAddList studentAddList, HttpServletRequest request, HttpServletResponse response) {

		System.out.println(studentAddList);
		Page<StudentAddList> page = studentMoreduMainService.queryDetail(new Page<StudentAddList>(request, response), studentAddList);
		return AjaxJson.success().put("page",page);
	}

	/**
	 * 学生德育档案列表数据
	 */
	@RequiresPermissions("moredumain:studentMoreduMain:list")
	@GetMapping("queryAbove")
	public AjaxJson queryAbove(StudentMoreduMain studentMoreduMain, HttpServletRequest request, HttpServletResponse response) {
		Page<StudentMoreduMain> page = studentMoreduMainService.queryAbove(new Page<StudentMoreduMain>(request, response), studentMoreduMain);
		return AjaxJson.success().put("page",page);
	}

	/**
	 * 根据Id获取学生德育档案数据
	 */
	@RequiresPermissions(value={"moredumain:studentMoreduMain:view","moredumain:studentMoreduMain:add","moredumain:studentMoreduMain:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(StudentMoreduMain studentMoreduMain) {
		return AjaxJson.success().put("studentMoreduMain", studentMoreduMain);
	}

	/**
	 * 保存学生德育档案
	 */
	@RequiresPermissions(value={"moredumain:studentMoreduMain:add","moredumain:studentMoreduMain:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(StudentMoreduMain studentMoreduMain, Model model) throws Exception{
		deleteCache();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(studentMoreduMain);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑表单保存
		studentMoreduMainService.save(studentMoreduMain);//保存
		return AjaxJson.success("保存学生德育档案成功");
	}
	@RequiresPermissions("moredumain:studentMoreduMain:list")
	@GetMapping("queryPinyin")
	public AjaxJson queryPinyin() {
		List<ScoreAcademicYear> academicYear = scoreAcademicYearService.findAcademicYear();
		List<PinYin1> nameList = studentMoreduMainService.queryName();
		List<PinYin1> instituteList = studentMoreduMainService.queryInstitute();
		List<PinYin1> teacherList = studentMoreduMainService.queryTeacher();
		return AjaxJson.success().put("nameList",nameList).put("instituteList",instituteList).put("teacherList",teacherList).put("academicYear", academicYear);
	}

	@GetMapping("getIpAddress")
	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip.contains(",")) {
			return ip.split(",")[0];
		} else {
			return ip;
		}
	}

	/**
	 * 批量删除学生德育档案
	 */
	@RequiresPermissions("moredumain:studentMoreduMain:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		deleteCache();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			studentMoreduMainService.delete(new StudentMoreduMain(id));
		}
		return AjaxJson.success("删除学生德育档案成功");
	}
	/**
	 * 根据班级查询总分接口
	 * class 班级
	 */
	@GetMapping("countPoint")
	public int countPoint(String classes) {
		return 	studentMoreduMainService.countPoint(classes);
	}
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("moredumain:studentMoreduMain:export")
    @GetMapping("export")
    public AjaxJson exportFile(StudentMoreduMain studentMoreduMain, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "学生德育档案"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<StudentMoreduMain> page = studentMoreduMainService.findPage(new Page<StudentMoreduMain>(request, response, -1), studentMoreduMain);
    		new ExportExcel("学生德育档案", StudentMoreduMain.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出学生德育档案记录失败！失败信息："+e.getMessage());
		}
    }
	/**
	 * 导出个人Word文件
	 */
	@RequiresPermissions("moredumain:studentMoreduMain:export")
//	@GetMapping("exportByIndividual")
	public void exportByIndividual1(StudentMoreduMain studentMoreduMain, HttpServletRequest request, HttpServletResponse response) {
		InputStream in = null;
		FileOutputStream out =null;
		try {
			if (studentMoreduMain.getQueryAcademicYear() != null && !"".equals(studentMoreduMain.getQueryAcademicYear())) {
				String[] interval = studentMoreduMain.getQueryAcademicYear().split(",");
				int minYear = 9999;
				int maxYear = 0;
				for(String temp : interval) {
					String[] ab = temp.split("-");
					int a = Integer.parseInt(ab[0]);
					int b = Integer.parseInt(ab[1]);
					if (a < minYear)
						minYear = a;
					if (b > maxYear)
						maxYear = b;
				}
				studentMoreduMain.setQueryAcademicYear(minYear + "-" + maxYear);
				DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
				LocalDate stdate = LocalDate.parse(minYear+"-09-01",dtf);
				LocalDate endate = LocalDate.parse(maxYear+"-08-01",dtf);
				studentMoreduMain.setStartDate(Date.from(stdate.atTime(LocalTime.MIDNIGHT).atZone(ZoneId.systemDefault()).toInstant()));
				studentMoreduMain.setEndDate(Date.from(endate.atTime(LocalTime.MIDNIGHT).atZone(ZoneId.systemDefault()).toInstant()));
			}
			//获取本地目录的word模板
			in = new FileInputStream(new File("C://software//score-final.docx"));
//			in = new FileInputStream(new File("D://score-final.docx"));

			//注册xdocreport实例并加载FreeMarker模板引擎
			IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Freemarker);
			//创建xdocreport上下文对象
			IContext context = report.createContext();
			StudentMoreduMain header = studentMoreduMainService.exportByIndividualAttribute(studentMoreduMain);
			System.out.println(header.getInstitute()+" "+header.getGrade()+" "+header.getClasse()+" "+header.getName()+" "+header.getStudentId()+" "+header.getCurrentMoraleduPoint());
			context.put("office",header.getInstitute());
			context.put("grade",header.getGrade());
			context.put("classn",header.getClasse());
			context.put("name",header.getName());
			context.put("no",header.getStudentId());
			context.put("currentMoraleduPoint",header.getCurrentMoraleduPoint());

			// 设置判空条件，当为空时会出现 全为null 的一条数据
			// 设置完成模板之后，让加分原因和减分原因都固定输出多少行，超出的不要，没有的添加空数据
			// 已经在数据层添加判空条件

			List<addPoint> addTemp = studentMoreduMainService.exportByIndividualAttributeAdd(studentMoreduMain);
			List<subPoint> subTemp = studentMoreduMainService.exportByIndividualAttributeSub(studentMoreduMain);

			List<addPointMap> add = new ArrayList<>();
			for (int i = 0; i < 40; i+=2) {
				if (i < addTemp.size()) {
					// 如果当前下标小于addTemp的长度，则使用数据
					addPoint a1 = addTemp.get(i);
					addPoint a2;
					if (i + 1 < addTemp.size()){
						a2 = addTemp.get(i + 1);
					} else {
						a2 = new addPoint("","","","");
					}
					add.add(new addPointMap(a1.getAddReason(), a1.getAddTime(), a1.getAddPoint(), a2.getAddReason(), a2.getAddTime(), a2.getAddPoint()));
				} else {
					add.add(new addPointMap("","","","","",""));
				}
			}

			List<subPointMap> sub = new ArrayList<>();
			for (int i = 0; i < 20; i+=2) {
				if (i < subTemp.size()) {
					subPoint s1 = subTemp.get(i);
					subPoint s2;
					if (i + 1 < subTemp.size()){
						s2 = subTemp.get(i + 1);
					} else {
						s2 = new subPoint("","","","");
					}
					sub.add(new subPointMap(s1.getSubReason(), s1.getSubTime(), s1.getSubPoint(), s2.getSubReason(), s2.getSubTime(), s2.getSubPoint()));
				} else {
					sub.add(new subPointMap("","","","","",""));
				}
			}

//			List<addPoint> add1 = new ArrayList<>();
//			List<subPoint> sub = new ArrayList<>();

//			add.add(new addPoint("加分原因", DateUtils.getDate("yyyyMMddHHmmss")+"", "123"));
//			add.add(new addPoint("加分原", DateUtils.getDate("yyyyMMddHHmmss")+"", "124"));
//			add.add(new addPoint("加分", DateUtils.getDate("yyyyMMddHHmmss")+"", "125"));
//			add1.add(new addPoint("加分原因1", DateUtils.getDate("yyyyMMddHHmmss")+"", "123"));
//			sub.add(new subPoint("减分原因1", DateUtils.getDate("yyyyMMddHHmmss")+"", "13"));
			context.put("add",add);
//			context.put("add1",add1);
			context.put("sub",sub);
			System.out.println("show"+sub.size());



//			List<UserTest> users = new ArrayList<>();
//			users.add(new UserTest(1,10,"你好","上海","KONO DIO DA","描述"));
//			users.add(new UserTest(2,18,"张三","北京","12957451","描述"));
//			users.add(new UserTest(3,20,"李四","武汉","个爱搜纪委","描述"));
//			users.add(new UserTest(4,25,"王五","广州","没出息捏","描述"));
//			users.add(new UserTest(5,25,"赵六","深圳","群殴IU为居民","描述"));
//			users.add(new UserTest(6,22,"钱七","杭州","IU前往合肥南","描述"));
//			//将需要替换的数据数据添加到上下文中
//			//其中key为word模板中的域名，value是需要替换的值
//			context.put("author","敬亭山");
//			context.put("date","2022年8月19日");
//			context.put("users",users);

			//创建字段元数据，需要表格才加下面这两行，否则不用
			FieldsMetadata fm = report.createFieldsMetadata();
			//Word模板中的表格数据对应的集合类型
			fm.load("add", addPoint.class, true);
//			fm.load("add1", addPoint.class, true);
			fm.load("sub", subPoint.class, true);
//			fm.load("users", UserTest.class, true);


			//浏览器端下载
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/msword");
//			response.setContentType("application/vnd.ms-excel");

			String fileName = "个人德育档案.docx";
//			response.setHeader("Content-Disposition", "attachment;filename="
//					.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
			response.setHeader("Content-Disposition", String.valueOf(URLEncoder.encode(fileName, "UTF-8")));
			report.process(context, response.getOutputStream());

		} catch (IOException e) {
		} catch (XDocReportException e) {
		} finally {
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@RequiresPermissions("moredumain:studentMoreduMain:export")
	@GetMapping("exportByIndividual")
	public void exportByIndividual(StudentMoreduMain studentMoreduMain, HttpServletRequest request, HttpServletResponse response){

		try{
			if (studentMoreduMain.getQueryAcademicYear() != null && !"".equals(studentMoreduMain.getQueryAcademicYear())) {
				String[] interval = studentMoreduMain.getQueryAcademicYear().split(",");
				int minYear = 9999;
				int maxYear = 0;
				for(String temp : interval) {
					String[] ab = temp.split("-");
					int a = Integer.parseInt(ab[0]);
					int b = Integer.parseInt(ab[1]);
					if (a < minYear)
						minYear = a;
					if (b > maxYear)
						maxYear = b;
				}
				studentMoreduMain.setQueryAcademicYear(minYear + "-" + maxYear);
				DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
				LocalDate stdate = LocalDate.parse(minYear+"-09-01",dtf);
				LocalDate endate = LocalDate.parse(maxYear+"-08-01",dtf);
				studentMoreduMain.setStartDate(Date.from(stdate.atTime(LocalTime.MIDNIGHT).atZone(ZoneId.systemDefault()).toInstant()));
				studentMoreduMain.setEndDate(Date.from(endate.atTime(LocalTime.MIDNIGHT).atZone(ZoneId.systemDefault()).toInstant()));
			}



			//获取模板路径
			String fullFilePath = "C://score.xlsx";
			//-final

			StudentMoreduMain header = studentMoreduMainService.exportByIndividualAttribute(studentMoreduMain);

			Map<String, Object> map = new HashMap<>();
			map.put("office",header.getInstitute());
			map.put("grade",header.getGrade());
			map.put("classn",header.getClasse());
			map.put("name",header.getName());
			map.put("no",header.getStudentId());
			map.put("currentMoraleduPoint",header.getCurrentMoraleduPoint());

			List<addPoint> add = studentMoreduMainService.exportByIndividualAttributeAdd(studentMoreduMain);
			List<subPoint> sub = studentMoreduMainService.exportByIndividualAttributeSub(studentMoreduMain);

//			List<addPoint> add = new ArrayList<>();
//			for (int i = 0; i < 20; i++) {
//				if (i < addTemp.size()) {
//					// 如果当前下标小于addTemp的长度，则使用数据
//					addPoint a = addTemp.get(i);
//					add.add(new addPoint(a.getAddReason(), a.getAddTime(), a.getAddPoint()));
//				} else {
//					add.add(new addPoint("1","1","1"));
//				}
//			}
//
//			List<subPoint> sub = new ArrayList<>();
//			for (int i = 0; i < 20; i++) {
//				if (i < subTemp.size()) {
//					subPoint s = subTemp.get(i);
//					sub.add(new subPoint(s.getSubReason(), s.getSubTime(), s.getSubPoint()));
//				} else {
//					sub.add(new subPoint("2","2","2"));
//				}
//			}
			if (add.size() < 18) {
				int temp = 18 - add.size();
				for (int i = 0; i < temp; i++) {
					add.add(new addPoint("","","",""));
				}
			}
			if (sub.size() < 17) {
				int temp = 17 - sub.size();
				for (int i = 0; i < temp; i++) {
					sub.add(new subPoint("","","",""));
				}
			}



			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/octet-stream");
			String fileName = header.getName() + "-个人德育档案.xlsx";
			response.setHeader("Content-Disposition",String.valueOf(URLEncoder.encode(fileName, "UTF-8")));

			//工作簿对象
			ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(fullFilePath).build();
			FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
			//工作区对象
			WriteSheet writeSheet = EasyExcel.writerSheet(0).build();

			excelWriter.fill(map,writeSheet);
			excelWriter.fill(new FillWrapper("data1",add),fillConfig,writeSheet);
			excelWriter.fill(new FillWrapper("data2",sub),fillConfig,writeSheet);

			int addStartRow = 5;
			int addEndRow = add.size() + 5;

			for (int i = addStartRow; i < addEndRow; i++) {
				excelWriter.merge(i,i,4,6);
			}

			int subStartRow = addEndRow + 3;
			int subEndRow = sub.size() + subStartRow;

			for (int i = subStartRow; i < subEndRow; i++) {
				excelWriter.merge(i,i,4,6);
			}

			excelWriter.finish();


		//输出excel
//			EasyExcel
//					.write(response.getOutputStream())
//					.autoCloseStream(true)
//					.withTemplate(fullFilePath)
//					.build()
////					.fill(map, EasyExcel.writerSheet(0).build())
//					.fill(add, fillConfig, EasyExcel.writerSheet(0).build())
//					.fill(sub, fillConfig, EasyExcel.writerSheet(0).build())
//					.finish();

		}catch (IOException e){
			e.printStackTrace();
		}
	}


	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("moredumain:studentMoreduMain:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		deleteCache();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<StudentMoreduMain> list = ei.getDataList(StudentMoreduMain.class);
			for (StudentMoreduMain studentMoreduMain : list){
				try{
					studentMoreduMainService.save(studentMoreduMain);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条学生德育档案记录。");
			}
			return AjaxJson.success( "已成功导入 "+successNum+" 条学生德育档案记录"+failureMsg);
		} catch (Exception e) {
			return AjaxJson.error("导入学生德育档案失败！失败信息："+e.getMessage());
		}
    }



	/**
	 * 下载导入学生德育档案数据模板
	 */
	@RequiresPermissions("moredumain:studentMoreduMain:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "学生德育档案数据导入模板.xlsx";
    		List<StudentMoreduMain> list = Lists.newArrayList();
    		new ExportExcel("学生德育档案数据", StudentMoreduMain.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }

	public void deleteCache () {
		String keyPre = "StudentMoreduMain";
		Set keys = redisTemplateObject.keys(keyPre + "*");
		if (ObjectUtil.isNotEmpty(keys)) {
			redisTemplateObject.delete(keys);
		}
	}


}